<template>
  <div style="background-color: #f6f6f6">
    <el-row>
      <el-col :span="20" :offset="2">
        <div class="form" style="padding-left: 20px;">
          <el-form :inline="true" :model="search" class="dw-form-inline" size="medium">
            <el-form-item label="租户名" v-if="currentRole=='租户'">
              <el-input v-model="search.key" placeholder="请输入要查询的租户名" clearable></el-input>
            </el-form-item>
            <el-form-item label="用户名" v-if="currentRole=='用户'">
              <el-input v-model="search.key" placeholder="请输入要查询的用户名" clearable></el-input>
            </el-form-item>
            <el-form-item label="答者名" v-if="currentRole=='答者'">
              <el-input v-model="search.key" placeholder="请输入要查询的答者名" clearable></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;" v-if="currentRole=='租户'">
              <el-button type="primary" icon="el-icon-search" @click="queryTenantsByKey(search.key)">查询</el-button>
            </el-form-item>
            <el-form-item style="margin-left: 20px;" v-if="currentRole=='用户'">
              <el-button type="primary" icon="el-icon-search" @click="queryUsersByKey(search.key)">查询</el-button>
            </el-form-item>
            <el-form-item style="margin-left: 20px;" v-if="currentRole=='答者'">
              <el-button type="primary" icon="el-icon-search" @click="queryAnswersByKey(search.key)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <div class="table-title">
            <el-row :span="24" type="flex" justify="space-between" align="middle">
              <el-col :span="4"><h3>权限管理</h3></el-col>
              <el-col :span="20" style="text-align: right;">
                <el-dropdown @command="handleCommand">
                  <el-button plain type="primary">{{ currentRole }}<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="0">租户</el-dropdown-item>
                    <el-dropdown-item command="1">用户</el-dropdown-item>
                    <el-dropdown-item command="2">答者</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </div>
          <el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%"
                    border :default-sort="{prop: 'username', order: 'ascending'}" @sort-change="handleSortChange" :header-cell-class-name="handleHeadAddClass" :key="tableKey">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="id" align="center" v-if="false"></el-table-column>
            <el-table-column label="序号" type="index" width="60" align="center">
              <template v-slot="scope">
                <span>{{(currentPage-1)*pageSize+1+scope.$index}}</span>
              </template>
            </el-table-column>
            <el-table-column :label="nameLabel" prop="username" sortable="custom" align="center"></el-table-column>
            <el-table-column label="电话" prop="telnumber" align="center"></el-table-column>
            <el-table-column label="创建时间" prop="createdDate" sortable="custom" align="center">
              <template v-slot="scope">
                <i class="el-icon-time"></i>
                {{ formatDate(scope.row.createdDate) }}
              </template>
            </el-table-column>
            <el-table-column label="最后登录时间" prop="lastLoginDate" sortable="custom" align="center">
              <template v-slot="scope">
                <i class="el-icon-time"></i>
                {{ formatDate(scope.row.lastLoginDate) }}
              </template>
            </el-table-column>
            <el-table-column label="身份" align="center">
              <el-tag :type="getTagType(this.currentRole)">
                {{ this.currentRole }}
              </el-tag>
            </el-table-column>
            <el-table-column label="登陆权限" prop="status" width="150" align="center">
              <template v-slot="scope">
                <el-tooltip :content="'权限: ' + formatStatus(scope.row.status)" placement="top">
                  <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="0"
                    :inactive-value="1"
                    @change="handleSwitchChange(scope.row)">
                  </el-switch>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {compare, DateFormat} from "../../utils/common";
import {
  modifyAnswerStatus,
  modifyTenantStatus,
  modifyUserStatus,
  queryTenantsByKey,
  queryUsersByKey
} from "../../api/admin";
import {queryAnswererByKey} from "../../api/admin";

export default {
  name: "authorityManagement",

  data() {
    return {
      currentRole: '租户',
      search: {
        key: ''
      },
      tableData: [],
      pageSize: 5,
      currentPage: 1,
      total: 0,
      // tableKey用于使表格重新渲染，解决切换身份时，排序标志显示异常的问题
      tableKey: ''
    }
  },

  computed: {
    nameLabel: function () {
      if (this.currentRole == '租户')
        return '租户名'
      if (this.currentRole == '用户')
        return '用户名'
      if (this.currentRole == '答者')
        return '答者名'
    }
  },

  methods: {
    queryTenantsByKey(key) {
      this.tableKey = 1
      // 调用模糊查询租户接口
      queryTenantsByKey(key).then((response) => {
        // console.log(response.data)
        this.tableData = response.data.data
        this.handleSortChange({prop: 'username', order: 'ascending'})
        this.total = response.data.data.length
      })
    },
    queryUsersByKey(key) {
      this.tableKey = 2
      // this.$refs.table.clearSort();
      // 调用模糊查询用户接口
      queryUsersByKey(key).then((response) => {
        console.log(response.data)
        this.tableData = response.data.data
        this.handleSortChange({prop: 'username', order: 'ascending'})
        this.total = response.data.data.length
      })
    },
    queryAnswersByKey(key) {
      this.tableKey = 3
      // this.$refs.table.clearSort();
      // 调用模糊查询答者接口
      queryAnswererByKey(key).then((response) => {
        this.tableData = response.data.data
        // console.log(response.data.data)
        this.handleSortChange({prop: 'username', order: 'ascending'})
        this.total = response.data.data.length
      })
    },
    changeTenantStatus(tenantId, tenantName, status) {
      const targetState = status == 0 ? 1 : 0
      // 调用修改租户状态接口
      modifyTenantStatus(tenantId, tenantName, status).then((response) => {
        if (response.data.code == '200') {
          this.$message.success(response.data.message)
        } else {
          this.$message.error(response.data.message)
        }
        this.queryTenantsByKey('')
      })
    },
    changeUserStatus(userId, userName, status) {
      const targetState = status == 0 ? 1 : 0
      // 调用修改用户状态接口
      modifyUserStatus(userId, userName, status).then((response) => {
        if (response.data.code == '200') {
          this.$message.success(response.data.message)
        } else {
          this.$message.error(response.data.message)
        }
        this.queryUsersByKey('')
      })
    },
    changeAnswerStatus(answerId, answerName, status) {
      const targetState = status == 0 ? 1 : 0
      // 调用修改答者状态接口
      modifyAnswerStatus(answerId, answerName, status).then((response) => {
        {
          if (response.data.code == '200') {
            this.$message.success(response.data.message)
          } else {
            this.$message.error(response.data.message)
          }
          this.queryAnswersByKey('')
        }
      })
    },
    formatDate(date) {
      return DateFormat(date)
    },
    formatStatus(status){
      const map = {
        0: '正常',
        1: '冻结'
      }
      return map[status]
    },
    getTagType(currentRole) {
      const map = {
        '租户': '',
        '用户': 'success',
        '答者': 'warning'
      }
      return map[currentRole]
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
    },
    handleCommand(command) {
      if (command == 0) {
        this.currentRole = '租户'
        this.queryTenantsByKey('')
      } else if (command == 1) {
        this.currentRole = '用户'
        this.queryUsersByKey('')
      } else if (command == 2) {
        this.currentRole = '答者'
        this.queryAnswersByKey('')
      }
    },
    handleSwitchChange(row) {
      if (this.currentRole == '租户') {
        this.changeTenantStatus(row.id, row.username, row.status)
      } else if (this.currentRole == '用户') {
        this.changeUserStatus(row.id, row.username, row.status)
      } else if (this.currentRole == '答者') {
        this.changeAnswerStatus(row.id, row.username, row.status)
      }
    },
    handleSortChange({prop, order}){
      this.tableData.sort(compare(prop, order))
    },
    handleHeadAddClass({column}){
      if(this.tableData[column.property]){
        column.order = this.tableData[column.property];
      }
    }
  },
  created() {
    this.queryTenantsByKey('')
  }
}
</script>

<style scoped>
.form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.table {
  background: white;
  padding: 20px;
}

.dw-table.dw-table-title h3 {
  padding: 0px;
  margin: 0px;
}

.pagination {
  padding-top: 20px;
  text-align: right;
}
</style>
